<?phpnamespace app\mobile\controller;use think\Db;use think\Cache;use think\Cookie;use think\Request;use think\Session;use think\Exception;use app\mobile\model\Ad;use app\mobile\model\Area;use app\mobile\common\Des;use app\mobile\model\Shop;use app\mobile\model\Config;use app\mobile\model\Coupon;use app\mobile\model\Member;use app\mobile\model\RushHour;use app\mobile\model\ShopHome;use app\mobile\model\Limited;use app\mobile\model\QuotHour;use app\mobile\model\ShopGoods;use app\mobile\model\GoodsType;use app\mobile\model\GroupGoods;use app\mobile\model\LimitedType;use app\mobile\model\MemberBrowse;use app\mobile\model\MemberAddress;use app\mobile\model\MemberCollect;use app\mobile\model\MemberOrder;use app\mobile\model\MemberPacket;use app\mobile\model\MemberCoupon;use app\mobile\model\ShopGoodsCombo;use app\mobile\model\ShopGoodsType;use app\mobile\model\ShopSpecAttr;use app\mobile\model\FreightTemplate;use app\mobile\model\MemberShoppingCart;use app\mobile\model\ShopGoodsEvaluate;use app\mobile\model\MemberOrderAttached;use app\mobile\model\TemporaryShoppingCart;use app\shop\controller\Location as LocationController;/** * Class UserCategory * @package app\mobile\controller    用户端分类 */class UserCategory extends BaseController{    /*     * 分类首页     */    public function index($cate_id = 'recommend')    {        $fetch_Arr = [];        if ($cate_id == 'recommend') {            //推荐分类            $fetch_Arr = GoodsType::where(['status' => '1', 'count' => '1', 'recommend' => '1'])                ->field('id,picUrl,title')                ->order(['sort' => 'asc'])->select();            $ad_find = Ad::where(['parenTid' => '18', 'start_time' => ['lt', time()], 'end_time' => ['gt', time()]])                ->field('picUrl,linkUrl,skip_type')                ->find();        } else {            $data_details = GoodsType::where(['status' => '1'])                ->field('id,parenTid,title,picUrl')                ->order(['sort' => 'asc'])                ->select();            $new_data_details = recursion_node($data_details);            foreach ($new_data_details as $v) {                if ($v['id'] == $cate_id) {                    $fetch_Arr = $v;                }            }            $ad_find = GoodsType::where(['id' => $cate_id, 'status' => '1'])                ->field('ad_img,linkUrl,skip_type')                ->find();        }        //左侧分类列表        $left_arr = GoodsType::where(['status' => '1', 'parenTid' => '0'])            ->field('id,title')            ->order(['sort' => 'asc'])            ->select();        return $this->fetch('', [            'left_arr' => $left_arr,            'data_details' => $fetch_Arr,            'ad_find' => $ad_find,        ]);    }    /*     * 分类搜索主页(店铺&商品)     */    public function search()    {        //热门搜索        $hot_search = explode(',', Cache::get('web_hot_search'));        //历史搜索        $history = !Cookie::has('search_record') ? [] : Cookie::get('search_record');        if (Request::instance()->isPost()) {            if (Cookie::has('search_record')) {                Cookie::delete('search_record');                return ['code' => 200, 'message' => '已清空历史'];            }            return ['code' => 400, 'message' => '暂无历史可清理'];        }        return $this->fetch('', [            'hot_search' => $hot_search,            'history' => $history,        ]);    }    /*     * 分类搜索结果展示页(店铺)     */    public function search_shop($search = '')    {        // 添加搜索记录        if ($search) {            self::search_record($search, 2);        }        // 获得数据        $arr = (new Shop())->where('title', 'like', '%' . $search . '%')->where('status', 1)            ->order(['sort' => 'desc', 'create_time' => 'desc'])            ->with(['shopGoods' => function ($query) {                //商品约束                $query->where(['state' => 1, 'status' => 1])->limit(4)->order(['sort' => 'desc', 'create_time' => 'desc'])                    ->field('id,member_id,thumb_img');            }])->field('member_id,title,logo,description,collect_number')->select();        $empty = '<p style="color: gray;text-align: center;margin-top: 10px;font-size: 12px">没有更多了</p>';        return $this->fetch('', [            'arr' => $arr,            'empty' => $empty,        ]);    }    /*     * 分类搜索结果展示页(条件商品列表)     */    public function search_goods(Request $request)    {        // 实例化        $model = new ShopGoods();        if ($request->isPost()) {            // 获取分页和分类            $page = $request->post('page', 1);            $type = $request->post('type', 0);            //排序 搜索的内容 价格区间 品牌            $condition = $model->get_condition($type);            $search = $request->param('search');            $price = $request->post('price');            $brand_id = $request->post('brand_id');            $cate_id = $request->post('cate_id');            $price_condition = [];            // 价格区间            if ($price) {                $price = explode('-', $price);                $price_condition['price'] = [['egt', $price[0]], ['elt', $price[1]]];            }            //存储搜索记录            if ($search) {                self::search_record($search, 1);            }            //平台分类id            $cate = $cate_id ?['goods_str' => ['like','%,'.$cate_id.',%']] : [];            $brand = [];            if ($brand_id) {                $brand = ['brand_id' => $brand_id];            }            //平台商品审核开关            $audit = Cache::get('web_commodity_audit');            $tj = $audit == 'Y' ? ['status' => 1, 'state' => 1] : ['state' => 1];            // 查询数据            $arr['data'] = $model->where($cate)->where('title', 'like', '%' . $search . '%')                ->where($price_condition)->where($brand)->order($condition)->field('id,member_id,title,price,sale_number,rebate_percentage,market_price,thumb_img')                ->limit(($page - 1) * 10, 10)->select();            // 查看是否是限时抢购活动 或者天天特价活动            $limited_type = (new LimitedType())->where('id', 2)->value('end_time');            foreach ($arr['data'] as &$value) {                $limit_info = (new Limited())->where('goods_id', $value['id'])->find();                if ($limit_info && $limited_type['end_time'] > time() && $limited_type['start_time'] < time()) {                    if ($limit_info['purchase_number'] > $limit_info['number']) {                        $value['price'] = $limit_info['price'];                    }                }                $special_price = (new GroupGoods())->where(['goods_id' => $value['id'], 'status' => 1])->value('price');                if ($special_price) {                    $value['price'] = $special_price;                }            }            $arr['pages'] = ceil($model->where($tj)->where($cate)->where('title', 'like', '%' . $search . '%')->where($price_condition)                    ->order($condition)->where($brand)->count() / 10);            return $arr;        }        return $this->fetch('');    }    /*     * 存储用户搜索记录     */    public function search_record($keyword, $type)    {        $info['keyword'] = $keyword;        if ($type == 1) {  //商品            $info['url'] = "search_goods?search=" . $keyword;        } elseif ($type == 2) {  //店铺            $info['url'] = "search_shop?type=2&search=" . $keyword;        }        $new_info[] = $info;        //是否含有搜索记录        if (Cookie::has('search_record')) {            $record = Cookie::get('search_record');            ////合并记录&检测是否有重复的记录            foreach ($record as $k => $value) {                if (isset($value['url']) && $info['url'] == $value['url'] && $info['keyword'] == $value['keyword']) {                    $new_info = $record;                    break;                } else {                    if (count($record) >= 10) {                        array_pop($record);  //删除最后一个记录                    }                    $new_info[] = $value;                }            }        }        //存入cookie        Cookie::set('search_record', $new_info);    }    /*     * 商品筛选     */    public function goods_shai(Request $request)    {        $title = $request->param('search', '');        return $this->fetch('', [            'search' => $title,        ]);    }    /*     * 商品详情     */    public function goods_details(Request $request)    {        $goods_id = $request->param('goods_id');        $freight_template_model = new FreightTemplate();        $member_address_model = new MemberAddress();        if (!$goods_id) {            throw new \Exception('not Empty');        }        // 详细信息        $info = ShopGoods::where(['id' => $goods_id])->field('id,member_id,market_price,title,sale_number,goods_id,describe,status,picUrl,label,goods_attr,rebate_percentage,state,picArr,activity,content,goods_attr,create_time as collection_status,price,rebate_percentage,freight_type,freight,sale_number')->with('shopGoodsFlag')->find();        if ($info['state'] != 1) {            $this->redirect('UserPort/error_shop');        }        //写入浏览记录        if (Session::has('member_id')) {            $this->record_browse($goods_id, $info['goods_id']);        }        self::flow($info['member_id']);        // 判断是否是限时抢购商品        $special_price = '';        $limit_status = '';        $hour = (int)date('H');        $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));        $ini['end_time'] = ['gt', $hour];        $quot_id = (new QuotHour)->where($ini)->field('id,name,start_time,end_time')->find();        $end_time = $beginToday + ($quot_id['end_time'] * 3600);        $son['goods_id'] = $goods_id;        $son['rush_id'] = ['eq',$quot_id['id']];        $limit_goods = (new RushHour)->where($son)->find();        if ($limit_goods) {            $special_price = $limit_goods['price'];            $limit_status = 'action';        }        // 判断是否天天特价        $special_info = (new GroupGoods())->where(['goods_id' => $goods_id, 'status' => 1])->find();        $special_status = '';        if (!empty($special_info)) {            $special_price = $special_info['price'];            $special_status = 'action';        }        //        return json($info);        $info['goods_attr'] = unserialize($info['goods_attr']);        $info['picArr'] = (array)unserialize($info['picArr']);        // 评论        $shopGoodsEvaluate = new ShopGoodsEvaluate();        $info['evaluate'] = $shopGoodsEvaluate->where(['goods_id' => $goods_id])->count();        // 'status' => 1        $info['evaluate_info'] = $shopGoodsEvaluate->where(['sun_shop_goods_evaluate.status' => '1', 'goods_id' => $goods_id])->order(['create_time' => 'desc'])            ->with(['member' => function ($e) {                $e->withField('id,nickname,avatar');            }])->find();        // 店铺        $info['shop'] = (new Shop)->where(['member_id' => $info['member_id']])->field('logo,title,description,phone,url,ship_address,mobile_url,type,url qq')->find();        // 此店铺是否有此商品优惠套餐        $shopGoodsCombo = new ShopGoodsCombo();        $info['combo'] = $shopGoodsCombo->where(['shop_id' => $info['member_id'], 'status' => 1])            ->where(['end_time' => ['gt', time()]])->order('id desc')            ->with(['shopGoodsComboSelected' => function ($e) {                $e->order('sort desc');            }])->find();        if ($info['combo']) {            foreach ($info['combo']['shopGoodsComboSelected'] as $value) {                $value->shopGoods;                $value->shopSpecAttr;            }        }        // 店铺推荐        $shop_goods = (new ShopGoods)->where(['member_id' => $info['member_id'], 'recommend' => '1', 'activity' => 2])->field('id,title,thumb_img,sale_number,price,rebate_percentage')            ->order(['sort' => 'desc', 'create_time' => 'desc'])->limit(4)->select();        //会员是否收藏此商品        $collect_status = (new MemberCollect())->where(['member_id' => Session::get('member_id'), 'type_id' => 1, 'collect_id' => $goods_id,])->count();        //空属性        $empty = '<div class="size" style="text-align: center;margin: 2% auto;">此商品无属性</div>';        //分享sdk参数        //$sign = (new WxConfig())->sdk_config(Request::instance()->url(true));        $sign = [];        // 商品标签        if (empty($info['label'])) {            $label = Db::name('Config')->where('varname', 'web_goods-label')->value('varvalue');        } else {            $label = $info['label'];        }        $label_array = explode(',', $label);        $my_address = $member_address_model->where('member_id',Session::get('member_id'))->select();        return $this->fetch('', [            'info'           => $info,            'jsSign'         => $sign,            'empty'          => $empty,            'freight'        => 0,            'address'        => '',            'address_id'     => '',            'shop_goods'     => $shop_goods,            'label'          => $label_array,            'my_address'     => $my_address,            'limit_status'   => $limit_status,            'special_status' => $special_status,            'special_price'  => $special_price,            'collect_status' => $collect_status,            'end_time'       => $end_time,        ]);    }    public function choseDetailAddress()    {        // 获取参数        $address_id = Request::instance()->param('id');        $shop_id = Request::instance()->param('shop');        // 实例化        $member_address_model = new MemberAddress();        $freight_template_model = new FreightTemplate();        // 获取数据        $address = $member_address_model->where('id',$address_id)->find();        // 计算运费        $con['member_id'] = $shop_id;        $con['area_id'] = ['like','%,'.$address['template_id'].',%'];        $freight = $freight_template_model->where($con)->value('price');        // 拼接参数        $address_id = $address['id'];        $address = $address['area_info'].$address['address'];        return ['code'=>200,'freight'=>$freight,'address'=>$address,'address_id'=>$address_id];    }    /*     * 记录会员浏览商品     */    public function record_browse($goods_id, $type_id)    {        $model = new MemberBrowse();        //查询数据库是否添加过此商品记录        $find = $model            ->where(['member_id' => Session::get('member_id'), 'goods_id' => $goods_id])            ->find();        if (!$find) {            $ini['member_id'] = Session::get('member_id');            $ini['goods_id'] = $goods_id;            $ini['goods_type'] = $type_id;            //添加记录            $model->save($ini);        }    }    /*     * 提交订单&生成订单     */    public function commit_order(Request $request)    {        if ($request->isPost()) {            $data = $request->post();  //trimData 转存的数据 message 客户留言            if (Session::get('flag') == 'once') {                Session::delete('flag');            } else {                return ['code' => 401, 'message' => '已提交过'];            }            $trimData = json_decode((new Des())->decrypt($data['trimData']), true);            //给单店铺赋留言            foreach ($trimData['shop'] as $k => &$value) {                $value['message'] = $data['message'][$k];            }            //启动事务处理            Db::startTrans();            try {                // 生成总订单号码                $order_number = createNumber();                // 处理                $attachedData = ''; //批量添加附表                $order_id_Arr = [];  //生成的订单id                foreach ($trimData['shop'] as $key => &$value) {                    // return json($value);                    // 更改优惠券状态                    if ($value['coupon_id']) {                        // 优惠券改变状态                        Db::name('member_coupon')->where([                            'member_id' => Session::get('member_id'),                            'status' => '2',                            'start_time' => ['lt', time()],                            //                            'end_time' => ['gt', time()],                            'id' => $value['coupon_id']                        ])->update(['status' => '1']);                    }                    // 更改红包状态                    if ($value['red_packet_id']) {                        // 红包改变状态                        Db::name('member_packet')->where([                            'member_id' => Session::get('member_id'),                            'status' => '2',                            'start_time' => ['lt', time()],                            'end_time' => ['gt', time()],                            'id' => $value['red_packet_id']                        ])->update(['status' => '1']);                    }                    // 店铺订单号                    // $shop_order_number = make_order(Session::get('member_id'));                    $shop_order_number = make_order($value['shop_id']);                    // 分销生成订单记录[用户id,单店铺价格合计,生成的店铺订单号,店铺id]                    $this->brokerage(Session::get('member_id'), $value['charges'], $shop_order_number, $value['shop_id']);                    // 主表信息                    $information = [                        'shop_id' => $value['shop_id'],                        'member_id' => Session::get('member_id'),                        'order_number' => $order_number,                        'shop_order_number' => $shop_order_number,                        'coupon_id' => $value['coupon_id'],                        'coupon_price' => $value['coupon_price'],                        'red_packet_id' => $value['red_packet_id'],                        'red_packet_price' => $value['red_packet_price'],                        'freight' => $value['freight'],                        'price' => $value['sum'],                        'message' => $value['message'],                        // 'goods'             => serialize($value['list']),                        'address_name' => $trimData['address']['name'],                        'address_phone' => $trimData['address']['phone'],                        'address_area' => $trimData['address']['area_info'],                        'address_site' => $trimData['address']['address'],                        'status' => '0',                        'way' => '未支付',                        // 'single_way' => 2,                        'create_time' => time(),                        'express_number' => '',                        'express_value' => '',                    ];                    // 插入订单主表                    $order_id = Db::name('member_order')->insertGetId($information);                    $order_id_Arr[] = $order_id;   //主订单表oid                    foreach ($value['list'] as &$val) {                        if (!empty($val['attr'])) {                            // 减少属性表库存                            $inventory_attr = Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->value('inventory');                            if ($inventory_attr < $val['number']) {                                return ['code' => 401, 'message' => $val['title'] . '(' . $val['attr'] . '),库存不足'];                            }                            Db::name('shop_spec_attr')->where(['attribute' => $val['attr'], 'goods_id' => $val['goods_id']])->setDec('inventory', $val['number']);                        }                        // 减少主表库存                        $inventory_find = Db::name('shop_goods')->where(['id' => $val['goods_id']])->value('inventory');                        if ($inventory_find < $val['number']) {                            return ['code' => 401, 'message' => $val['title'] . ',库存不足'];                        }                        Db::name('shop_goods')->where('id', $val['goods_id'])->setDec('inventory', $val['number']);                        Db::name('shop_goods')->where('id', $val['goods_id'])->setInc('sale_number', $val['number']);                        $attachedData[] = [                            'order_id' => $order_id,                            'order_number' => $order_number,                            'shop_order_number' => $shop_order_number,                            'goods_id' => $val['goods_id'],                            'attr' => $val['attr'],                            'number' => $val['number'],                            'price' => $val['price'],                            'title' => $val['title'],                            'thumb_img' => $val['thumb_img'],                            'rebate_percentage' => $val['rebate_percentage'],                            'limited_status' => $val['limited_status'],                            'status' => '2'                        ];                        //是否为特价商品                        if (!empty($val['limited_status'])) {                            //查找特价商品的限制数量和已购买数量                            $limited = Db::name('rush_hour')->where(['goods_id' => $val['goods_id']])->field('number,purchase_number')->find();                            if (!empty($limited)) {                                if (($limited['purchase_number'] + $val['number']) > $limited['number']) return ['code' => 402, 'message' => '特价商品数量不够,请调整购物车再进行购买'];                                // 是否是特价                                Db::name('rush_hour')->where(['goods_id' => $val['goods_id']])->setInc('purchase_number', $val['number']);                                // 特价数量                                $good_limit_a = Db::name('member_limited')->where(['goods_id' => $val['goods_id'], 'member_id' => Session::get('member_id')])->find();                                if ($good_limit_a) {                                    Db::name('member_limited')->where(['goods_id' => $val['goods_id'], 'member_id' => Session::get('member_id')])->setInc('number', $val['number']);                                } else {                                    Db::name('member_limited')->insert([                                        'member_id' => Session::get('member_id'),                                        'goods_id' => $val['goods_id'],                                        'number' => $val['number'],                                    ]);                                }                            }                        }                    }                }                // 批量插入附表                Db::name('member_order_attached')->insertAll($attachedData);                // 删除此次购物车的记录                if (isset($trimData['cart_id'])) {                    MemberShoppingCart::destroy($trimData['cart_id']);                }                // 提交事务                Db::commit();                return ['code' => 200, 'oid' => implode(',', $order_id_Arr)];            } catch (\Exception $e) {                //回滚事务                Db::rollback();                return ['code' => 0, 'message' => $e->getMessage()];            }        }    }    /**     * 支付拍卖订单     */    public function auction()    {        $oid = Request::instance()->param('oid');        $find = Db::name('auction_order')->where('id', $oid)->find();        //返回支付密码        $pass = Member::where('id', Session::get('member_id'))->value('pay_pass');        $info = Member::where('id', Session::get('member_id'))->field('username,wechat_id')->find();        $information = 'auction|' . Session::get('member_id') . '|' . $find['order_number'];  //支付宝attach        //微信配置参数        if (self::is_weixin()) {            $param = (new Wxpay())->auction($find['price'], $find['order_number']);            $is_weixin = 1;        } else {            $param = '{}';            $is_weixin = 2;        }        return $this->fetch('', [            'pass' => $pass,            'info' => $info,            'information' => $information,            'param' => $param,            'total' => $find['price'],            'is_weixin' => $is_weixin        ]);    }    /*     * 选择支付方式     */    public function choose_pay_type(Request $request)    {        //返回支付密码        $pass = Member::where('id', Session::get('member_id'))->value('pay_pass');        $info = Member::where('id', Session::get('member_id'))->field('username,wechat_id')->find();        $oid = $request->param('oid');        //查询订单总价        $totalArr = (new MemberOrder())->where('id', 'in', $oid)->where('status', 0)->field('sum(price) as total_price,sum(freight) as total_freight,order_number,shop_order_number')->find();        $total = $totalArr['total_price'];        //查询主订单号        $orderNumber = MemberOrder::where('id', 'in', $oid)->value('order_number');        // 获取支付宝回调的参数        //我的订单->单店铺商品付款        $alipayInformation = MemberOrderAttached::where(['order_id' => $oid])->select();        //可能是多店铺商品付款        if (stristr($oid, ',')) {            $alipayInformation = MemberOrderAttached::where(['order_number' => $orderNumber])->select();        }        $goodIds = "";        foreach ($alipayInformation as $value) {            $goodIds .= $value['goods_id'] . ',';        }        $goodsNew = rtrim($goodIds, ',');   //移除右侧的逗号        $information = 'pay|' . Session::get('member_id') . '|' . $goodsNew;  //支付宝attach        $out_trade_no = $totalArr['shop_order_number'];  //单店铺        if (stristr($oid, ',')) {  //多店铺(购物车提交)            $out_trade_no = $totalArr['order_number'];        }        //微信配置参数        if (self::is_weixin()) {            $param = (new Wxpay())->pay($information, $total, $out_trade_no);            // $param = '{} ';            $is_weixin = 1;        } else {            $param = '{}';            $is_weixin = 2;        }        // $param = '{}';        return $this->fetch('', [            'oid' => $oid,            'pass' => $pass,            'info' => $info,            'information' => $information,            'param' => $param,            'total' => $total,            'is_weixin' => $is_weixin        ]);    }    public function is_weixin()    {        if (strpos($_SERVER['HTTP_USER_AGENT'],                'MicroMessenger') !== false        ) {            return true;        }        return false;    }    //余额支付    public function balance(Request $request)    {        if ($request->isPost()) {            $model = new MemberOrder();            $data = $request->post();    //oid 总订单id  p用户输入的密码            $pass = (new Member)->where('id', Session::get('member_id'))->value('pay_pass');            if (md5(md5($data['p'])) != $pass) {                return ['code' => 400, 'message' => '密码不正确'];            }            //查询订单总价            $totalArr = $model->where('id', 'in', $data['oid'])->where('status', 0)->field('sum(price) as total_price,sum(freight) as total_freight')->find();            $pay_money = bcadd($totalArr['total_price'], $totalArr['total_freight'], 2);            //用户余额            $balance = (new Member)->where('id', Session::get('member_id'))->value('balance');            if ($balance < $pay_money) {                return ['code' => 402, 'message' => '余额不足'];            }            //查找订单信息            $orderInfo = $model->where('id', 'in', $data['oid'])->with('memberOrderAttached')->select();            foreach ($orderInfo as $value) {                if ($value['status'] == 1) {                    return ['code' => 403, 'message' => '已经支付过了'];                }            }            //启动事务处理订单            Db::startTrans();            try {                //余额扣除                $result = Db::name('member')->where('id', Session::get('member_id'))->setDec('balance', $pay_money);                if ($result) {                    //更新总订单状态                    Db::name('member_order')->where('id', 'in', $data['oid'])->update(['status' => '1', 'way' => '余额支付', 'pay_time' => time()]);                    //店铺订单号                    $order_number = [];                    foreach ($orderInfo as $value) {                        $order_number[] = $value['shop_order_number'];                    }                    // 减少库存                    $inventory = Db::name('member_order_attached')->where(['shop_order_number' => ['in', implode(',', $order_number)]])                        ->field('goods_id,attr,number,price,shop_order_number')->select();                    // 消费记录                    $ini = [                        'member_id' => Session::get('member_id'),                        'type_id' => '3',                        'balance' => ($balance - $pay_money),                        'price' => $pay_money, 'way' => '余额支付',                        'status' => '1',                        'order_number' => count($order_number) == 1 ? reset($order_number) : $orderInfo[0]->order_number,                        'create_time' => time()                    ];                    Db::name('member_withdraw')->insert($ini);                    // 是否为首单(是则增加积分)                    $find = Db::name('integral_record')->where(['member_id' => Session::get('member_id'), 'type' => '购买'])->value('id');                    //首单支付额外增加积分                    if (!$find) {                        // 送积分                        Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', Cache::get('web_integral_goods'));                        // 添加记录                        Db::name('integral_record')->insert(                            [                                'member_id'   => Session::get('member_id'),                                'type_id'     => '1',                                'type'        => '购买',                                'integral'    => Cache::get('web_integral_goods'),                                'title'       => '（首单）购买商品',                                'create_time' => time()                            ]                        );                    }                    // Db::name('integral_record')->insert(                    //     [                    //         'member_id'   => Session::get('member_id'),                    //         'type_id'     => '1',                    //         'type'        => '购买',                    //         'integral'    => ceil($pay_money),                    //         // 'title'       => '购买商品订单号为:' . count($order_number) == 1 ? reset($order_number) : $orderInfo[0]->order_number,                    //         'title'       => '购买商品订单号为:' . count($order_number) == 1 ? reset($order_number) : $orderInfo[0]->order_number,                    //         'create_time' => time()                    //     ]                    // );                    // 添加积分记录                    // 购物增加积分                    $sin = [];                    $total_integral = 0;                    foreach ($inventory as $value) {                        $percentage = Cache::get('web_deduction_percentage');                        $one_integral = ceil(bcmul($value['price'], $value['number'], 0) * $percentage * 0.01);                        $sin[] = [                            'member_id'   => Session::get('member_id'),                            'type_id'     => '1',                            'type'        => '购买',                            'integral'    => $one_integral,                            'title'       => $value['shop_order_number'],                            'create_time' => time()                        ];                        $total_integral += $one_integral;                    }                    Db::name('integral_record')->insertAll($sin);                    Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', $total_integral);                }                Db::commit();                return ['code' => 200, 'message' => '交易成功'];            } catch (\Exception $e) {                Db::rollback();                return ['code' => 500, 'message' => '网络繁忙,请重试'];            }        }    }    /*     * 下订单时佣金分配     */    public function brokerage($user_id, $price, $order_number, $shop_id)    {        // 分销返利        $hierarchy = Db::name('member_distribution')->where(['referrals_id' => $user_id])->order(['level' => 'desc'])->value('hierarchy');        // 判断是否存在        if (!empty($hierarchy)) {            $hierarchy = explode(',', $hierarchy);      // 变成数组            array_shift($hierarchy);                    // 去掉第一个key            array_pop($hierarchy);                      // 去掉最后一个key            $hierarchy = array_slice($hierarchy, -3);   // 倒数3个            rsort($hierarchy);                       // 逆向排序        }        // 查看是否开启店铺分销 Y是启用 N是未启用（N默认平台）        if (Cache::get('web_distribution') == 'Y') {            $shop = Db::name('shop')->where(['member_id' => $shop_id])->field('one_ratio,two_ratio,three_ratio')->find();            // 本人分销佣金 给自己返钱            if (isset($user_id)) {                // 产生的佣金                $brokerage = bcmul($price, ($shop['one_ratio'] / 100), 2);                // 增加待收益佣金 和 总数                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('general_income', $brokerage);                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('to_yield', $brokerage);                // 添加分销订单                Db::name('member_distribution_order')->insert([                    'member_id' => $user_id,                    'distribution_id' => $user_id,                    'brokerage' => $brokerage,                    'order_number' => $order_number,                    'create_time' => time()                ]);            }            // 一级分销佣金            if (isset($hierarchy[0])) {                // 产生的佣金                $brokerage = bcmul($price, ($shop['two_ratio'] / 100), 2);                // 增加待收益佣金 和 总数                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('general_income', $brokerage);                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('to_yield', $brokerage);                // 添加分销订单                Db::name('member_distribution_order')                    ->insert([                        'member_id' => $user_id,                        'distribution_id' => $hierarchy[0],                        'brokerage' => $brokerage,                        'order_number' => $order_number,                        'create_time' => time()                    ]);            }            // 二级分销佣金            if (isset($hierarchy[1])) {                // 产生的佣金                $brokerage = bcmul($price, ($shop['three_ratio'] / 100), 2);                // 增加待收益佣金 和 总数                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('general_income', $brokerage);                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('to_yield', $brokerage);                // 添加分销订单                Db::name('member_distribution_order')                    ->insert([                        'member_id' => $user_id,                        'distribution_id' => $hierarchy[1],                        'brokerage' => $brokerage,                        'order_number' => $order_number,                        'create_time' => time()                    ]);            }        } else {            // 本人佣金            if (isset($user_id)) {                // 增加待收益佣金 和 总数                $brokerage = bcmul($price, (Cache::get('web_one_ratio') / 100), 2);                // 增加佣金                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('general_income', $brokerage);                Db::name('member_brokerage')->where(['member_id' => $user_id])->setInc('to_yield', $brokerage);                // 添加分销订单                Db::name('member_distribution_order')->insert([                    'member_id' => $user_id,                    'distribution_id' => $user_id,                    'brokerage' => $brokerage,                    'order_number' => $order_number,                    'create_time' => time()                ]);            }            // 一级分销佣金            if (isset($hierarchy[0])) {                // 增加待收益佣金 和 总数                $brokerage = bcmul($price, (Cache::get('web_two_ratio') / 100), 2);                // 增加佣金                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('general_income', $brokerage);                Db::name('member_brokerage')->where(['member_id' => $hierarchy[0]])->setInc('to_yield', $brokerage);                // 添加分销订单                Db::name('member_distribution_order')                    ->insert([                        'member_id' => $user_id,                        'distribution_id' => $hierarchy[0],                        'brokerage' => $brokerage,                        'order_number' => $order_number,                        'create_time' => time()                    ]);            }            // 二级分销佣金            if (isset($hierarchy[1])) {                // 产生的佣金                $brokerage = bcmul($price, (Cache::get('web_three_ratio') / 100), 2);                // 增加待收益佣金 和 总数                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('general_income', $brokerage);                Db::name('member_brokerage')->where(['member_id' => $hierarchy[1]])->setInc('to_yield', $brokerage);                // 添加分销订单                Db::name('member_distribution_order')                    ->insert([                        'member_id' => $user_id,                        'distribution_id' => $hierarchy[1],                        'brokerage' => $brokerage,                        'order_number' => $order_number,                        'create_time' => time()                    ]);            }        }    }    /*     * 确认订单 展示页     * (来源:立即购买或购物车)     */    public function order_yes(Request $request)    {        //购物车物品id        $act = $request->param('act');        $cart_id = $request->param('cart_id');        $red_shop_id = $request->param('red_shop_id', '');        $address_id = $request->param('address_id', '');        $coupon_id = $request->get('coupon_id', '');        // 实例化        $cartModel = new MemberShoppingCart();        $temporaryShoppingCart = new TemporaryShoppingCart();        $couponModel = new MemberCoupon();        $redPacketModel = new MemberPacket();        //用户选择的所有优惠券        $idStr = '';        $obj = [];        if ($coupon_id) {            $obj = json_decode($coupon_id, true);            $idStr = implode(',', $obj);        }        $couponData = $couponModel->where(['id' => ['in', $idStr]])->field('id,member_id,title,actual_price')->select();        //用户选择红包        $red_packet_id = $request->param('red_packet_id', '');        $packetData = $redPacketModel->where('id', $red_packet_id)->field('id,actual_price,title')->find();        //从购物车表查出商品信息        if ($act == "temporary") {            $data = $temporaryShoppingCart->where('sun_temporary_shopping_cart.id', 'in', $cart_id)                ->with(['shopGoods' => function ($e) {                    $e->withField('id,member_id,rebate_percentage,charges,title,price,freight,thumb_img,goods_str');                }])->select();        }else{            $data = $cartModel->where('sun_member_shopping_cart.id', 'in', $cart_id)                ->with(['shopGoods' => function ($e) {                    $e->withField('id,member_id,rebate_percentage,charges,title,price,freight,thumb_img,goods_str');                }])->select();        }        // return (json($data));        //同一店铺商品合并        $opt = [];        foreach ($data as $key => $value) {            $value->shopGoods->shop;            $opt[$value->shopGoods->shop->title]['shop_id'] = $value->shopGoods->member_id;            $opt[$value->shopGoods->shop->title]['data'][$key] = $value;        }        //用户默认收货地址        $address = (new MemberAddress)->where(['member_id' => Session::get('member_id'), 'status' => 1])->field('name,phone,address,area_info,template_id')->find();        //用户选择收货地址来替换默认        if ($address_id && $address_id != 'undefined') {            $address = (new MemberAddress)->where('id', $address_id)->field('name,phone,address,area_info,template_id')->find();        }        //立即抢购        if ($request->has('limited', 'param')) {            $opt = [];            $limitArr = explode('|', $request->param('limited'));  //抢购的商品id,属性attr,数量num            //查找限购信息            if ($limitArr && count($limitArr) == 3) {                $limitInfo = (new RushHour())->where(['sun_rush_hour.goods_id' => $limitArr[0]])->field('id,goods_id,number,price')                    ->with(['shopGoods' => function ($e) {                        $e->withField('id,member_id,rebate_percentage,title,price,freight,thumb_img,goods_str,charges');                    }])->find();                //数量不足                if ($limitInfo['number'] < $limitArr[2]) {                    throw new \Exception('Number is not enough');                }                $limitInfo['limited_status'] = 1;                $limitInfo['number'] = $limitArr[2];                $limitInfo['attr'] = Db::name('shop_spec_attr')->where('id', $limitArr[1])->value('attribute');                $limitInfo['member_id'] = Session::get('member_id');                $limitInfo->shopGoods->shop;                $opt[$limitInfo->shopGoods->shop->title]['shop_id'] = $limitInfo->shopGoods->member_id;                $opt[$limitInfo->shopGoods->shop->title]['data'][] = $limitInfo;            }        }        //套餐购买        if ($request->has('combo', 'param')) {            //查找套餐信息            $opt = [];            $comboArr = explode('|', $request->param('combo'));   //套餐id,属性串,套餐数量            $combo_data = self::combo_list($request->param('combo'), 'order_yes');            $attr = explode(',', $comboArr[1]);            foreach ($combo_data->shopGoodsComboSelected as $key => $item) {                $item->shopGoods->shop;                $attr_find = [];                //有属性                if ($attr[$key]) {                    $attr_find = Db::name('shopSpecAttr')->where(['id' => $attr[$key]])->field('id,price,attribute')->find();                }                unset($item->shopSpecAttr, $item->sort, $item->combo_id, $item->goods_attr_id);                $item['price'] = $attr_find ? $attr_find['price'] : $item->shopGoods->price;                $item['charges'] = $item->shopGoods->charges;                $item['number'] = $comboArr[2];    //购买数量                $item['member_id'] = Session::get('member_id');                $item['limited_status'] = 0;                $item['goods_id'] = $item->shopGoods->id;  //商品id                $item['attr'] = $attr_find ? $attr_find['attribute'] : '';   //属性                $opt[$item->shopGoods->shop->title]['shop_id'] = $combo_data->shop_id;                $opt[$item->shopGoods->shop->title]['combo_price'] = bcmul($combo_data->combo_price, $comboArr[2], 2);                $opt[$item->shopGoods->shop->title]['data'][] = $item;            }        }        $total['zong_price'] = 0;        $total['zong_number'] = 0;        $goods_str = '';    //所有商品分类串        foreach ($opt as &$v) {   /*展示数据*/            $v['total_number'] = 0;    //单店铺商品数量合计            $v['total_price'] = 0;      //单店铺价格合计            $v['total_freight'] = 0;    //单店铺运费合计            $v['coupon_id'] = '';       //此店铺优惠券id初始化            $v['coupon_title'] = '';    //此店铺优惠券标题初始化            $v['coupon_actual_price'] = '';    //优惠券的实际金额            $v['red_id'] = '';          //此店铺红包id初始化            $v['red_title'] = '';       //此店铺红包标题初始化            $v['red_actual_price'] = '';    //红包的实际金额            if ($couponData) {                foreach ($couponData as $sk => $item) {                    if (array_search($item['id'], $obj) == $v['shop_id']) {    //哪家店铺选择的优惠券放在哪家                        $v['coupon_id'] = $item['id'];                        $v['coupon_title'] = $item['title'];                        $v['coupon_actual_price'] = $item['actual_price'];                        $v['total_price'] = bcsub($v['total_price'], $item['actual_price'], 2);   //相应总额减去优惠券实际金额                    }                }            }            if ($red_shop_id == $v['shop_id']) {  //哪家店铺选择的红包放在哪家                $v['red_id'] = $packetData['id'];                $v['red_title'] = $packetData['title'];                $v['red_actual_price'] = $packetData['actual_price'];                $v['total_price'] = bcsub($v['total_price'], $packetData['actual_price'], 2);   //相应总额减去红包实际金额            }            foreach ($v['data'] as $vv) {                $v['total_number'] += $vv['number'];                $v['total_price'] = bcadd($v['total_price'], bcmul($vv['price'], $vv['number'], 2), 2);                $son['member_id'] = $v['shop_id'];                $son['area_id'] = ['like','%,'.$address['template_id'].',%'];                $vv['freight'] =db('shop_goods')->where('id',$vv['goods_id'])->value('freight');                //$v['total_freight'] = bcmul($vv['freight'],$vv['number'],2);                $v['total_freight'] = $vv['freight'];                // 运费计算//                if ($request->has('combo', 'param')||$request->has('limited', 'param')){//                    $v['total_freight'] = 0;//                }else{//                    $vv['freight'] =db('shop_goods')->where('id',$vv['goods_id'])->value('freight');//                    $v['total_freight'] = bcmul($vv['freight'],$vv['number'],2);//                    $freight = (new FreightTemplate())->where($son)->value('price');////                    if ($freight) {////                        $v['total_freight'] = $freight;////                    }else{////                        $v['total_freight'] = 0;////                    }//                }                $goods_str = $vv->shopGoods['goods_str'];            }            $total['zong_number'] += $v['total_number'];    //订单总商品数量            $v['total_sum'] = bcadd($v['total_price'], $v['total_freight'], 2);            $total['zong_price'] = bcadd($total['zong_price'], $v['total_sum'], 2);      //订单总价            if (isset($v['combo_price'])) {                $v['total_price'] = $v['combo_price'];   //[单店铺商品价格合计]套餐价                $v['total_sum'] = $v['combo_price'];   //套餐是店主设置的合计价格(包含运费)                $total['zong_price'] = $v['combo_price'];   //[支付价]套餐是立即购买,所以只有一次循环            }        }        // return json($opt);        $shop = [];        $num = 0;        $pay_money = 0;        foreach ($opt as $key => $value) {   /*订单数据*/            $shop[$num]['title'] = $key;    //店铺名称            $shop[$num]['shop_id'] = $value['shop_id'];  //店铺id            $shop[$num]['coupon_id'] = '';   //使用的优惠券id            $shop[$num]['coupon_price'] = 0;   //优惠券金额            $shop[$num]['red_packet_id'] = '';  //使用的红包id            $shop[$num]['red_packet_price'] = 0;  //红包金额            $shop[$num]['freight'] = $value['total_freight'];   //单店铺运费合计            $shop[$num]['price'] = $value['total_price'];   //单店铺合计            $shop[$num]['sum'] = $value['total_sum'];    //上面两个合计的总和            $shop[$num]['charges'] = 0; // 店铺返利金额            if ($couponData) {                foreach ($couponData as $sk => $_c) {                    if (array_search($_c['id'], $obj) == $value['shop_id']) {                        $shop[$num]['coupon_id'] = $_c['id'];  //优惠券id                        $shop[$num]['coupon_price'] = $_c['actual_price'];  //优惠券实际金额                    }                }            }            if ($red_shop_id == $value['shop_id'] && $packetData) {  //哪个店铺选择的红包                $shop[$num]['red_packet_id'] = $red_packet_id;                $shop[$num]['red_packet_price'] = $packetData['actual_price'];   //红包实际金额            }            foreach ($value['data'] as $k => $item) {                //商品集合                $shop[$num]['list'][$k]['goods_id'] = $item->goods_id;                $shop[$num]['list'][$k]['attr'] = $item->attr;                $shop[$num]['list'][$k]['number'] = $item->number;                $shop[$num]['list'][$k]['price'] = $item->price;                $shop[$num]['list'][$k]['member_id'] = $item->shopGoods->member_id;                $shop[$num]['list'][$k]['title'] = $item->shopGoods->title;                $shop[$num]['list'][$k]['thumb_img'] = $item->shopGoods->thumb_img;                $shop[$num]['list'][$k]['rebate_percentage'] = $item->shopGoods->rebate_percentage;                $shop[$num]['list'][$k]['charges'] = bcmul($item->shopGoods->charges, $item->number, 2);                $shop[$num]['list'][$k]['limited_status'] = $item->limited_status;                $shop[$num]['charges'] = bcadd($shop[$num]['charges'], $shop[$num]['list'][$k]['charges'], 2);            }            $pay_money = bcadd($pay_money, $shop[$num]['sum'], 2);            $num++;        }        //转存订单的数据        $trimData['user_id'] = Session::get('member_id');        $trimData['address'] = $address;        $trimData['shop'] = $shop;        $trimData['cart_id'] = $cart_id;        $trimData['pay_money'] = $pay_money;  //交易金额        //防表单重复提交        if (!Session::get('flag')) {            Session::set('flag', 'once');        }        return $this->fetch('', [            'address' => $address,            'data' => $opt,            'total' => $total,            'goods_str' => $goods_str,            'trimData' => (new Des())->encrypt(json_encode($trimData)),        ]);    }    /*     * 检测套餐是否符合条件     */    public function check_combo(Request $request)    {        if ($request->isPost()) {            $combo_id = $request->post('combo_id');            $combo = (new ShopGoodsCombo())                ->where(['id' => $combo_id, 'status' => 1])                ->with('shopGoodsComboSelected')                ->find();            if (!$combo) {                return ['code' => 400, 'message' => '套餐不存在'];            }            if (!$combo->shopGoodsComboSelected) {                return ['code' => 401, 'message' => '套餐内无商品'];            }            if ($combo['end_time'] < time()) {                return ['code' => 402, 'message' => '套餐已结束'];            }            return ['code' => 200, 'message' => '符合条件'];        }    }    /*     * 店铺&商品收藏     */    public function member_collect(Request $request)    {        if ($request->isPost()) {            $id = $request->post('id');            $type = $request->post('type');   // 1 商品  2店铺            //检测会员是否收藏过此商品 或 店铺            $model = new MemberCollect();            $goodsModel = new ShopGoods();            $shopModel = new Shop();            $status = $model                ->where(['type_id' => $type, 'collect_id' => $id, 'member_id' => Session::get('member_id')])                ->find();            Db::startTrans();  //启动事务            try {                if ($status) { //取消收藏                    MemberCollect::destroy($status['id']);                    if ($type == 1) {  //收藏商品                        $goodsModel->where('id', $id)->setDec('collect');  //收藏数减1                    } else {                        $shopModel->where('member_id', $id)->setDec('collect_number');                    }                    Db::commit();                    return ['code' => 100, 'message' => '取消收藏成功'];                } else {  //收藏                    $model->isUpdate(false)->save(['type_id' => $type, 'collect_id' => $id, 'member_id' => Session::get('member_id'), 'create_time' => time()]);                    if ($type == 1) {  //收藏商品                        $goodsModel->where('id', $id)->setInc('collect');  //收藏数加1                    } else {                        $shopModel->where('member_id', $id)->setInc('collect_number');                    }                    Db::commit();                    return ['code' => 200, 'message' => '收藏成功'];                }            } catch (\Exception $e) {                Db::rollback();                return ['code' => 0, 'message' => '网络繁忙,请重试'];            }        }    }    /*     * 优惠套餐     */    public function combo_list($combo_id, $flag = '')    {        $data = (new ShopGoodsCombo())->where('id', $combo_id)->where(['end_time' => ['gt', time()]])            ->with(['shopGoodsComboSelected' => function ($e) {                $e->order('sort desc');            }])->find();        if ($data) {            foreach ($data['shopGoodsComboSelected'] as $value) {                $value->shopGoods;                $value->shopSpecAttr;            }        }        $goodsArr = [];        //运费合计        $freight = 0;        foreach ($data->shopGoodsComboSelected as $value) {            $goodsArr[] = $value->goods_id;            $freight += $value->shopGoods->freight;        }        $info = ShopGoods::where('id', 'in', implode(',', $goodsArr))            ->field('id,member_id,title,sale_number,picUrl,goods_attr,rebate_percentage,picArr,content,goods_attr,create_time as collection_status,price,rebate_percentage,freight_type,freight,sale_number')            ->order('id desc')            ->select();        foreach ($info as &$value) {            //            if ($value['goods_attr'] != 'N;'){            $value['goods_attr'] = unserialize($value['goods_attr']);            //            }        }        if ($flag == 'order_yes') {   //立即购买(确认订单)提供数据            return $data;        }        //        return json($data);        return $this->fetch('', [            'data' => $data,            'freight' => $freight,            'info' => $info,        ]);    }    /*     * 确定新的属性     */    public function new_attr()    {        if (Request::instance()->isPost()) {            $id = Request::instance()->post('goods_id');            $attribute = Request::instance()->post('text');            $find = (new ShopSpecAttr())->where(['goods_id' => $id, 'attribute' => $attribute])->field(['id', 'market_price', 'price', 'inventory'])->find();            $inventory = 0;            if (!$attribute) {  //无属性总库存                $inventory = (new ShopGoods())->where(['id' => $id])->value('inventory');            }            return empty($find) ? ['inventory' => $inventory] : $find;        }    }    /*     * 领取店铺优惠券列表     */    public function get_ticket(Request $request)    {        if ($request->isPost()) {            $model = new Coupon();            $page = $request->post('page', 1);            $shop_id = $request->post('shop_id');            $result['data'] = $model->where(['member_id' => $shop_id, 'status' => '1', 'end_time' => ['gt', time()]])                ->field('id,title,actual_price,virtual_price,number,content,start_time,end_time,sort as receive_status')                ->with(['memberCoupon' => function ($e) {                    $e                        ->where('member_id', Session::get('member_id'))                        ->field('id,coupon_id,status,member_id');                }])                ->order(['sort' => 'desc'])                ->limit(($page - 1) * 5, 5)                ->select();            //总页数            $result['pages'] = ceil($model                    ->where(['member_id' => $shop_id, 'status' => '1', 'end_time' => ['gt', time()]])                    ->count('id') / 5            );            return $result;        }        return $this->fetch('');    }    /*     * 领取店铺优惠券     */    public function ticket_act()    {        if (Request::instance()->isPost()) {            $id = Request::instance()->post('id');            $model = new Coupon();            $info = $model->where('id', $id)->find();            $opt = $info->getData();            //检测是否为自己店铺优惠券            if ($opt['member_id'] == Session::get('member_id')) {                return ['code' => 400, 'message' => '不能领取自己店铺的优惠券'];            }            $opt['shop_id'] = $opt['member_id'];            $opt['coupon_id'] = $opt['id'];            $opt['member_id'] = Session::get('member_id');            $opt['status'] = 2;            $opt['create_time'] = time();            unset($opt['id']);            // 启动事务            Db::startTrans();            try {                // 添加用户优惠券                (new MemberCoupon())->allowField(true)->isUpdate(false)->save($opt);                // 店铺优惠券自减一                Db::name('coupon')->where('id', $id)->setDec('number');                // 提交事务                Db::commit();                return ['code' => 200, 'message' => '领取成功'];            } catch (\Exception $e) {                // 回滚事务                Db::rollback();                return ['code' => 0, 'message' => '网络繁忙,请重试'];            }        }    }    /*     * 商品评论     */    public function goods_evaluate(Request $request)    {        // 获取参数        $goods_id = $request->param('goods_id');        // 实例化        $evaluate = new ShopGoodsEvaluate();        if ($request->isPost()) {            // 获取参数            $goods_id = $request->post('goods_id');            $grade = $request->post('grade', '0');            $page = $request->post('page');            //已审核            // $condition['sun_shop_goods_evaluate.status'] = ['eq', '1'];            $condition['goods_id'] = ['eq', $goods_id];            // 晒图            if ($request->post('img') == 1) $condition['picArr'] = ['neq', ''];            // 获取评级            switch ($grade) {                case 5:                    $condition['grade'] = ['gt', 3];                    break;                case 3:                    $condition['grade'] = ['eq', 3];                    break;                case 1:                    $condition['grade'] = ['lt', 3];                    break;                default:                    $condition['grade'] = ['gt', '0'];            }            // 获取数据            $res = $evaluate->where($condition)->with('member')->order(['create_time' => 'desc'])->limit(($page - 1) * 10, 10)->select();            // 闭包            $result['data'] = array_map(function ($dispose) {                if ($dispose->picArr) {                    $dispose->picArr = unserialize($dispose->picArr);                }                return $dispose;            }, $res);            //总页数            $result['pages'] = ceil($evaluate->where($condition)->count('id') / 10);            return $result;        }        // 统计        // $statistics['all_count'] = ShopGoodsEvaluate::where(['sun_shop_goods_evaluate.status' => '1', 'goods_id' => $goods_id])->with('member')->count();  // 全部        // $statistics['good_count'] = ShopGoodsEvaluate::where(['sun_shop_goods_evaluate.status' => '1', 'goods_id' => $goods_id, 'grade' => ['gt', '3']])->with('member')->count();  // 好评        // $statistics['centre_count'] = ShopGoodsEvaluate::where(['sun_shop_goods_evaluate.status' => '1', 'goods_id' => $goods_id, 'grade' => '3'])->with('member')->count();  // 中评        // $statistics['bad_count'] = ShopGoodsEvaluate::where(['sun_shop_goods_evaluate.status' => '1', 'goods_id' => $goods_id, 'grade' => ['lt', '3']])->with('member')->count();  // 差评        // $statistics['img_count'] = ShopGoodsEvaluate::where(['sun_shop_goods_evaluate.status' => '1', 'goods_id' => $goods_id, 'picArr' => ['neq', '']])->with('member')->count();  // 晒图        // 全部  好评 中评 差评 晒图        $statistics['all_count'] = $evaluate->where(['goods_id' => $goods_id])->with('member')->count();        $statistics['good_count'] = $evaluate->where(['goods_id' => $goods_id, 'grade' => ['gt', '3']])->with('member')->count();        $statistics['centre_count'] = $evaluate->where(['goods_id' => $goods_id, 'grade' => '3'])->with('member')->count();        $statistics['bad_count'] = $evaluate->where(['goods_id' => $goods_id, 'grade' => ['lt', '3']])->with('member')->count();        $statistics['img_count'] = $evaluate->where(['goods_id' => $goods_id, 'picArr' => ['neq', '']])->with('member')->count();        return $this->fetch('', [            'statistics' => $statistics,        ]);    }    // 店铺详情之公共头部    public function public_head($shop_id)    {        if (!$shop_id) throw new Exception('操作异常');        //店铺信息        if (Request::instance()->has('goods_id', 'get')) {            Session::set('goods_id', Request::instance()->get('goods_id'));        }        $shopInfo = (new Shop())->where('member_id', $shop_id)->field('type,logo,top_banner,title,name,description,mobile_url,url qq,collect_number,phone,create_time,m_banner,type,banner')            ->find();        if (empty($shopInfo)) $this->redirect('user_port/index');        //店铺被收藏数        $shopInfo['collect'] = (new MemberCollect())            ->where(['type_id' => 2, 'collect_id' => $shop_id])->count('id');        $shopInfo['goods_id'] = Session::get('goods_id');        return $shopInfo;    }    /*     * 店铺详情之首页     */    public function shop_index($shop_id)    {        if (!$shop_id) throw new Exception('操作异常');        $shopInfo = self::public_head($shop_id);        $result['pic'] = (new ShopHome)->where(['member_id' => $shop_id])->field('member_id', true)->find();        self::flow($shop_id);        //店铺首页展示3枚优惠券        $result['coupon'] = (new Coupon)->where(['member_id' => $shop_id, 'status' => '1', 'end_time' => ['gt', time()]])            ->field('id,actual_price,virtual_price,number,sort as receive_status')->order(['sort' => 'rand'])->limit('3')->select();        //查找用户领取的优惠券        $user_coupon = (new MemberCoupon)->where(['member_id' => Session::get('member_id')])->column('coupon_id');        //会员是否收藏此店铺        $collect_status = (new MemberCollect())->where(['type_id' => 2, 'collect_id' => $shop_id, 'member_id' => Session::get('member_id')])->count();        if (Request::instance()->isPost()) {            $shop_id = Request::instance()->post('shop_id');            $page = Request::instance()->post('page');            $condition = ['member_id' => $shop_id, 'state' => '1', 'activity' => 2];            //搜索内容            $search = Request::instance()->post('search');            // 是否开启审核            if (Cache::get('web_commodity_audit') == 'Y') $condition['status'] = ['eq', '1'];            $goods_list['data'] = (new ShopGoods)->where($condition)->field('id,title,price,thumb_img,sale_number')                ->where('title|describe', 'like', '%' . $search . '%')->order(['shop_sort' => 'desc', 'sort' => 'desc', 'create_time' => 'desc'])                ->limit(($page - 1) * 6, 6)->select();            //总数量            $goods_list['pages'] = ceil(count((new ShopGoods)->where($condition)->where('title|describe', 'like', '%' . $search . '%')->select()) / 6);            return $goods_list;        }        return $this->fetch('', [            'result' => $result,            'shopInfo' => $shopInfo,            'user_coupon' => $user_coupon,            'collect_status' => $collect_status,        ]);    }    /*     * 店铺详情之全部商品     */    public function all_goods($shop_id)    {        if (!$shop_id) throw new Exception('操作异常');        // 店铺头信息        $shopInfo = self::public_head($shop_id);        $result = (new ShopHome)->where(['member_id' => $shop_id])->field('member_id', true)->find();        // 店铺优惠券        $result['coupon'] = (new Coupon)->where(['member_id' => $shop_id, 'status' => '1', 'end_time' => ['gt', time()]])            ->field('id,actual_price,virtual_price,number,sort as receive_status')->order(['sort' => 'desc'])->limit('3')->select();        //会员是否收藏此店铺        $collect_status = (new MemberCollect())->where(['type_id' => 2, 'collect_id' => $shop_id, 'member_id' => Session::get('member_id')])->count();        //查找用户领取的优惠券        $user_coupon = (new MemberCoupon)->where(['member_id' => 3])->column('coupon_id');        if (Request::instance()->isPost()) {            $shop_id = Request::instance()->post('shop_id');            $page = Request::instance()->post('page', 1);            $order = ['shop_sort' => 'desc', 'sort' => 'desc', 'create_time' => 'desc'];            $search = Request::instance()->post('search', '');            $cate_id = Request::instance()->post('cate_id', 0) == 0 ? [] : ['parenTid' => Request::instance()->post('cate_id', '')];            // if (Request::instance()->has('type')) {            //     $order = (new ShopGoods())->condition(Request::instance()->post('type'));            // }            $condition = ['member_id' => $shop_id, 'state' => '1', 'status' => 1];            // 是否开启审核            if (((new Config())->where('varname', 'web_commodity_audit')->value('varname')) == 'Y') $condition['status'] = ['eq', '1'];            // 店铺商品            $goods_list['data'] = (new ShopGoods)->where($condition)->where('title', 'like', '%' . $search . '%')                ->where($cate_id)->field('id,title,price,thumb_img,sale_number,rebate_percentage')->order($order)->limit(($page - 1) * 6, 6)->select();            $limited_type = (new LimitedType())->where('id', 2)->value('end_time');            foreach ($goods_list['data'] as &$value) {                $limit_info = (new Limited())->where('goods_id', $value['id'])->value('price');                if ($limit_info && $limited_type['end_time'] > time() && $limited_type['start_time'] < time()) {                    if ($limit_info['purchase_number'] > $limit_info['number']) {                        $value['price'] = $limit_info['price'];                    }                }                $special_price = (new GroupGoods())->where(['goods_id' => $value['id'], 'status' => 1])->value('price');                if ($special_price) {                    $value['price'] = $special_price;                }            }            //总数量            $goods_list['pages'] = ceil(count((new ShopGoods)->where($condition)->where($cate_id)->where('title', 'like', '%' . $search . '%')->select()) / 6);            return $goods_list;        }        return $this->fetch('', [            'result' => $result,            'shopInfo' => $shopInfo,            'user_coupon' => $user_coupon,            'collect_status' => $collect_status,        ]);    }    /*     * 店铺详情之促销商品     */    public function sales_promote($shop_id)    {        if (!$shop_id) throw new Exception('操作异常');        //会员是否收藏此店铺        $collect_status = (new MemberCollect())->where(['type_id' => 2, 'collect_id' => $shop_id, 'member_id' => Session::get('member_id')])->count();        $shopInfo = self::public_head($shop_id);        if (Request::instance()->isPost()) {            //搜索内容            $shop_id = Request::instance()->post('shop_id');            $page = Request::instance()->post('page');            $search = Request::instance()->post('search');            $order = ['shop_sort' => 'desc', 'sort' => 'desc', 'create_time' => 'desc'];            $condition = ['member_id' => $shop_id, 'state' => '1', 'promotion' => 1];            // 是否开启审核            if (((new Config())->where('varname', 'web_commodity_audit')->value('varname')) == 'Y') $condition['status'] = ['eq', '1'];            $goods_list['data'] = (new ShopGoods)->where($condition)->field('id,title,price,thumb_img,sale_number,rebate_percentage')                ->where('title|describe', 'like', '%' . $search . '%')->order($order)->limit(($page - 1) * 6, 6)->select();            //总数量            $goods_list['pages'] = ceil(count((new ShopGoods)->where($condition)->where('title|describe', 'like', '%' . $search . '%')->select()) / 6);            return $goods_list;        }        return $this->fetch('', [            'shopInfo' => $shopInfo,            'collect_status' => $collect_status,        ]);    }    /*     * 店铺首页之上新 (本月)     */    public function new_list($shop_id)    {        if (!$shop_id) throw new Exception('操作异常');        //会员是否收藏此店铺        $collect_status = (new MemberCollect())            ->where(['type_id' => 2, 'collect_id' => $shop_id, 'member_id' => Session::get('member_id')])            ->count();        // 店铺信息        $shopInfo = self::public_head($shop_id);        $shop_id = Request::instance()->param('shop_id');        $search = Request::instance()->post('search');   //搜索内容        // 搜索条件        $condition['state'] = ['eq', 1];        $condition['member_id'] = ['eq', $shop_id];        // 是否开启审核        if (Cache::get('web_commodity_audit') == 'Y') $condition['status'] = ['eq', '1'];        $goods_list = ShopGoods::where($condition)->field('id,title,price,thumb_img,sale_number,rebate_percentage,date_time')            ->where('title|describe', 'like', '%' . $search . '%')->order(['create_time' => 'desc'])            ->limit(10)->select();        return $this->fetch('', [            'shopInfo' => $shopInfo,            'goods_list' => arrayGrouping($goods_list, 'date_time', 'date', 'list'),            'collect_status' => $collect_status,        ]);    }    /*     * 店铺简介     */    public function shop_intro($shop_id)    {        if (!$shop_id) throw new Exception('操作异常');        //会员是否收藏此店铺        $collect_status = (new MemberCollect())            ->where(['type_id' => 2, 'collect_id' => $shop_id, 'member_id' => Session::get('member_id')])            ->count();        $shopInfo = self::public_head($shop_id);        return $this->fetch('', [            'shopInfo' => $shopInfo,            'collect_status' => $collect_status,        ]);    }    /*     * 店铺商品分类     */    public function shop_goods_cate($shop_id)    {        //查找显示的店铺商品分类        $result = ShopGoodsType::where(['member_id' => $shop_id, 'status' => 1])->field('id,parenTid,title,member_id')->select();        return $this->fetch('', [            'arr' => recursion_node($result),        ]);    }    /*     * 店铺全部商品     */    public function shop_all_goods()    {        return $this->fetch('');    }    /*     * 品牌分类     */    public function goods_type(Request $request)    {        // 实例化        $model = new ShopGoods();        // 平台审核配置        $audit = (new  Config())->where('varname', 'web_commodity_audit')->value('varvalue');        if ($request->isPost()) {            $page = $request->post('page', 1);            $type = $request->post('type', 0);            $goods_type = ($request->post('goods_type') == -1) ? [] : ['goods_id' => $request->post('goods_type')];            $condition = $model->get_condition($type);            //平台分类id            $cate_id = $request->post('cate_id');            $cate = $cate_id ? ['goods_id' => $cate_id] : [];            $search = $request->post('search');            $tj = $audit == 'Y' ? ['status' => 1, 'state' => 1] : ['state' => 1];            $arr['data'] = $model                ->where($tj)                ->where($cate)                ->where($goods_type)->order($condition)                ->field('id,member_id,title,price,sale_number,rebate_percentage,thumb_img')                ->limit(($page - 1) * 10, 10)                ->select();            $arr['pages'] = ceil($model->where($tj)->where('title', 'like', '%' . $search . '%')->order($condition)->count('id') / 10);            return $arr;        }        return $this->fetch('');    }    public function flow($shop_id)    {        // 今日日期        $hit_time = date('Y-m-d');        $find = Db::name('shop_hit')->where(['shop_id' => $shop_id, 'hit_time' => $hit_time])->find();        if (empty($find)) {            Db::name('shop_hit')->insert(['shop_id' => $shop_id, 'hit_time' => $hit_time, 'hits' => 1]);        } else {            Db::name('shop_hit')->where(['shop_id' => $shop_id, 'hit_time' => $hit_time])->setInc('hits');        }    }}